package com.kintreda.tools.upload;

import com.google.gson.Gson;
import com.kintreda.common.config.exception.CommonBaseErrorCode;
import com.kintreda.common.config.exception.CommonBaseException;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.util.UUID;

/**
 * 图片上传
 * @author zhou_shun
 * @date 2019-11-12 下午 20:46
 */

@Slf4j
@Component
public class QiniuUpload {

    private static String[] fileSuffix = {"jpg", "bmp", "jpeg", "png", "gif","mp4","3gp","webm","flv","mkv","doc","docx","xls","xlsx","pdf"};

    private static String accessKey;

    private static String secretKey;

    private static String bucket;

    private static String domain;

    /**
     * 七牛云
     *
     * @param file
     * @return
     */
    public static String upload(MultipartFile file) {
        Response response = null;
        DefaultPutRet set = null;

        String imgUrl = domain;

        //判断图片是否为空
        if (file.isEmpty()) {
            throw new CommonBaseException(CommonBaseErrorCode.USER_PICTURE_IS_EMPTY);
        }
        // 判断是否是合法的文件后缀
        int dotPos = file.getOriginalFilename().lastIndexOf(".");
        if (dotPos < 0) {
            throw new CommonBaseException(CommonBaseErrorCode.USER_PICTURE_FORMAT_ERROR);
        }
        String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
        boolean flag = false;
        for (String s : fileSuffix) {
            if (s.equals(fileExt)) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            throw new CommonBaseException(CommonBaseErrorCode.USER_PICTURE_FORMAT_ERROR);
        }
        //判断文件大小
        if (file.getSize() > 30 * 1024 * 1024) {
            throw new CommonBaseException(CommonBaseErrorCode.USER_PICTURE_OVERSIZE);
        }

        //构造一个带指定Zone对象的配置类
        Configuration configuration = new Configuration(Zone.autoZone());
        UploadManager manager = new UploadManager(configuration);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = LocalDate.now()+"/"+UUID.randomUUID().toString().replaceAll("\\-", "")+'.'+fileExt;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            response = manager.put(file.getInputStream(), key, upToken, null, null);
            //解析上传成功的结果
            set = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            imgUrl += set.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            log.error(r.toString());
            throw new CommonBaseException(CommonBaseErrorCode.USER_PICTURE_FAIL);
        } catch (IOException e) {
            log.error("上传失败", e);
            throw new CommonBaseException(CommonBaseErrorCode.USER_PICTURE_FAIL);
        }
        return imgUrl;
    }

    @Value("${upload.qiniu.accessKey}")
    public void setAccessKey(String accessKey) {
        QiniuUpload.accessKey = accessKey;
    }

    @Value("${upload.qiniu.secretKey}")
    public void setSecretKey(String secretKey) {
        QiniuUpload.secretKey = secretKey;
    }

    @Value("${upload.qiniu.bucket}")
    public void setBucket(String bucket) {
        QiniuUpload.bucket = bucket;
    }

    @Value("${upload.qiniu.domain}")
    public void setDomain(String domain) {
        QiniuUpload.domain = domain;
    }

}
